using GameFrameWork;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class HitState : IFsmState
{
    private float m_HitDuration = 0.2f; // 受击状态持续时间（秒）
    private float m_ElapsedTime = 0f;

    public void Enter(Entity entity, params object[] args)
    {
        m_ElapsedTime = 0f; // 重置计时器

        // 检查是否有传入伤害值
        if (args != null && args.Length > 0 && args[0] != null)
        {
            long damage = 0;
            
            // 尝试将第一个参数转换为伤害值
            if (args[0] is long longDamage)
            {
                damage = longDamage;
            }
            else if (args[0] is int intDamage)
            {
                damage = intDamage;
            }
            else if (args[0] is float floatDamage)
            {
                damage = (long)Math.Round(floatDamage);
            }
            else
            {
                // 尝试转换
                if (long.TryParse(args[0].ToString(), out long parsedDamage))
                {
                    damage = parsedDamage;
                }
            }

            // 如果有有效的伤害值，调用 TakeDamage
            if (damage > 0 && entity.HealthComponent != null)
            {
                Logger.Log($"【HitState】 Enter ===>>> {entity.name} 受到伤害: {damage}");
                entity.HealthComponent.TakeDamage(damage);
            }
        }
 
        long hp = entity.HealthComponent.CurHealth;
        if (entity.Animator != null)
        {
            entity.Animator.SetInteger("hp", (int)hp);
        }
        Logger.Log($"【HitState】 Enter ===>>> {entity.name}, CurHealth:{hp}, PreviousState:{entity.FSMComponent.PreviousState}");
    }

    public void Exit(Entity entity, params object[] args)
    {
        m_ElapsedTime = 0f;
    }

    public void Process(Entity entity, params object[] args)
    {
        if (entity == null) return;
        
        // 检查是否死亡
        if (entity.HealthComponent.IsDead)
        {
            entity.FSMComponent.ChangeStatus(FSMType.Dead);
            return;
        }

        // 更新受击状态计时器
        m_ElapsedTime += Time.deltaTime;
        
        // 受击状态持续时间结束后，切换回之前的状态
        if (m_ElapsedTime >= m_HitDuration)
        {
            FSMType previousState = entity.FSMComponent.PreviousState;
            
            // 如果之前的状态无效（None或Hit），根据实体类型选择默认状态
            if (previousState == FSMType.None || previousState == FSMType.Hit)
            {
                // 僵尸默认回到移动状态，植物默认回到空闲状态
                if (entity is Zombie)
                {
                    previousState = FSMType.Move;
                }
                else
                {
                    previousState = FSMType.Idle;
                }
            }
            
            Logger.Log($"HitState Process ===>>> {entity.name} 受击状态结束，切换回 {previousState} 状态");
            entity.FSMComponent.ChangeStatus(previousState);
        }
    }
}
